<template>
  <div class="common-layout">
    <el-container>
      <!-- 顶部Header -->
      <el-header class="header">
        <HeadInfo/>
        <span class="header-title">会议室预定系统</span>
      </el-header>

      <!-- 主体内容 -->
      <el-container style="overflow: hidden;">
        <!-- 左侧菜单栏 -->
        <el-aside width="200px" class="aside-container">
          <el-menu
            :default-active="activeIndex"
            @select="handleMenuSelect"
            class="aside-menu"
            background-color="#f0f2f5"
            text-color="#303133"
            active-text-color="#409EFF"
          >
            <!-- 菜单内容 -->
            <div v-for="(item, index) in filteredMenuList" :key="index">
              <el-sub-menu
                v-if="item.children?.length"
                :index="(index + 1).toString()"
              >
                <template #title>
                  <el-icon>
                    <component :is="item.icon" />
                  </el-icon>
                  <span>{{ item.label }}</span>
                </template>
                <el-menu-item
                  v-for="(child, childIndex) in item.children"
                  :key="childIndex"
                  :index="`${index + 1}-${childIndex + 1}`"
                >
                <template #title>
                  <el-icon v-if="child.icon">
                    <component :is="child.icon" />
                  </el-icon>
                 <span>{{ child.label }}</span>
                </template>
                </el-menu-item>
              </el-sub-menu>
              <el-menu-item
                v-else
                :index="(index + 1).toString()"
              >
                <el-icon>
                  <component :is="item.icon" />
                </el-icon>
                <span>{{ item.label }}</span>
              </el-menu-item>
            </div>
          </el-menu>
        </el-aside>

        <!-- 右侧内容区域 -->
        <el-container>
          <el-main class="main-content">
            <router-view />
          </el-main>
          <el-footer class="footer">© 2025 会议室预定系统</el-footer>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
  import { ref, watch, onMounted, onUnmounted, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { 
    HomeFilled,
    User,
    House,
    DocumentChecked,
    Setting, 
    TopLeft,
    Memo,
    Notification,
  } from '@element-plus/icons-vue'
  import HeadInfo from '@/components/HeadInfo.vue'
  import { useUserStore } from '@/stores'
  import { storeToRefs } from 'pinia'

  const router = useRouter()

  const userStore = useUserStore()
  const { userInfo } = storeToRefs(userStore) 

  // 当前激活菜单项（字符串的数字格式）
  const activeIndex = ref('1')

  // 路由路径到菜单索引的映射
  const findMenuIndex = (path) => {
    let result = ''
    filteredMenuList.value.forEach((item, index) => {
      // 检查主菜单项
      if (item.path === path) {
        result = (index + 1).toString()
      }
      // 检查子菜单项
      if (item.children) {
        item.children.forEach((child, childIndex) => {
          if (child.path === path) {
            result = `${index + 1}-${childIndex + 1}`
          }
        })
      }
    })
    return result
  }

  // 初始化激活菜单项
  const updateActiveIndex = () => {
    //console.log('更新激活菜单项:', router.currentRoute.value.path)
    activeIndex.value = findMenuIndex(router.currentRoute.value.path)
  }

  onMounted(() => {
      userStore.getUserInfo();
      updateActiveIndex();
      // console.log(filteredMenuList.value);
    }
  )

  // 菜单选择处理
  const handleMenuSelect = (index) => {
    let targetPath = ''
    // 解析数字索引
    if (index.includes('-')) {
      // 子菜单格式 1-1
      const [parentIndex, childIndex] = index.split('-').map(Number)
      targetPath = filteredMenuList.value[parentIndex - 1]?.children[childIndex - 1]?.path
    } else {
      // 主菜单格式 1
      targetPath = filteredMenuList.value[index - 1]?.path
    }

    if (targetPath!=''&&targetPath!=undefined) {
      router.push(targetPath)
    } else {
      ElMessage.error('路由配置错误')
    }
  }

  // 监听路由变化
  watch(
    () => router.currentRoute.value.path,
    (newPath) => {
      updateActiveIndex()
    }
  )

  // 监听角色变化
  const roleWatcher = watch(
    ()=>userInfo.value.userRole, (newVal,oldVal) => {
      if (oldVal!=newVal) {
        console.log("角色切换",oldVal,newVal)
        router.replace('/prior/login')//明明没有切换，为什么会变
      }
    },
    {immediate:false}
  )

  onUnmounted(() => {
    roleWatcher()
  })

  // 菜单数据  需要有多份?
  const originalMenuList = [
    {
      path: '/main/home',
      icon: HomeFilled,
      label: '主页面',
    },
    {
      icon: User,
      label: '用户页面',
      children: [
        {
          path: '/main/PersonIndex/PersonInfo',
          label: '个人资料',
        },
        {
          path: '/main/PersonIndex/Logout',
          icon:TopLeft,
          label: '登出'
        }
      ]
    },
    {
      path:'/main/RoomReview',
      icon: House,
      label:'会议室预订',
    },
    {
      path:'/main/ReviewInfo',
      icon: Memo,
      label:'订单查看',
    },
    {
      path:'/main/CancelReview',
      icon: House,
      label:'退订服务',
    },
    {
      path:'/main/CancelInfo',
      icon: Memo,
      label:'退订查看',
    },
    {
      path:'/main/CancelManage',
      icon: DocumentChecked,
      label:'退订管理',
    },
    {
      path:'/main/RoomCheck',
      icon: Notification,
      label:'会议室维护',
    },
    {
      path:'/main/RoomManage',
      icon: Setting,
      label:'会议室管理',
    },
    {
      path:'/main/UserManage',
      icon: DocumentChecked,
      label:'用户管理',
    }
  ]

  // 计算当前角色的菜单列表
  const filteredMenuList = computed(() => {
    const filtered =originalMenuList.map(item => {
      if (item.children) {
        const filteredChildren = item.children.filter(child => {
          const route = router.getRoutes().find(route => route.path === child.path);//获取所有路由对象并且找到对应的路由对象
          return route?.meta?.visiable && route?.meta?.roles.includes(userInfo.value.userRole);//过滤
        });//获得子菜单项中在范围内的导航
        return filteredChildren.length ? { ...item, children: filteredChildren } : null;
      } else {
        const route = router.getRoutes().find(route => route.path === item.path);
        return route?.meta?.visiable && route?.meta?.roles.includes(userInfo.value.userRole) ? item : null;//单一路由处理
      }
    }).filter(item => item !== null);
    return filtered.length > 0 ? filtered : originalMenuList ;//map遍历,filter去除空对象,如果真的没有才是原来的菜单兜底
  })
</script>

<style lang="scss" scoped>
.el-container {
  height: 100%;
}
.common-layout{
  height: 100vh;
  border-radius: 10px;
  .header{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    height: 60px;
    line-height: 60px;
    background-color: #409eff; /* 主蓝色 */
    color: white;
    text-align: center;
    .header-title{
      font-size: 20px;
    }
  }
  .aside-container{
    border-right: 1px solid #e6e6e6; /*#e6e6e6; */
    overflow: hidden;
    .aside-menu{
      background-color: #f0f2f5; /* 菜单背景 */
      color: #303133;           /* 文字颜色 */
      border-right: 1px solid #dcdfe6;
      overflow-y: auto;
      height: 100%;
      :deep(.el-menu-item) {
        height: 48px;
        line-height: 48px;
        padding: 0 20px;
        color: #303133;
      }
      :deep(.el-menu-item.is-active),
      :deep(.el-sub-menu__title.is-active) {
        background-color: #36a3f7 !important; /* 激活项背景 */
        color: white !important;             /* 激活项文字 */
      }

      :deep(.el-sub-menu__title:hover),
      :deep(.el-menu-item:hover) {
        background-color: #82cae7 !important; /* 悬停背景 */
        color:#303133 !important;
      }

      :deep(.el-sub-menu .el-menu-item) {
        padding-left: 40px !important;
      }
    }
  }
  .main-content{
    padding: 20px;
    background-color: whitesmoke; /* 菜单背景色 */
    flex: 1;
  }
  .footer{
    height: 60px;
    line-height: 60px;
    background-color: #409eff; /* 主蓝色 */
    color: white;
    text-align: center;
  }
}
</style>